// 订餐服务功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化订餐功能
    initFoodOrder();
    
    // 初始化订单历史
    loadRecentOrders();
});

// 初始化订餐功能
function initFoodOrder() {
    const qtyControls = document.querySelectorAll('.qty-controls');
    
    // 川菜馆控制元素
    const sichuanSubmitBtn = document.getElementById('sichuanSubmitOrderBtn');
    const sichuanSummaryCount = document.getElementById('sichuanSummaryCount');
    const sichuanSummaryTotal = document.getElementById('sichuanSummaryTotal');
    
    // 粤菜馆控制元素
    const cantonSubmitBtn = document.getElementById('cantonSubmitOrderBtn');
    const cantonSummaryCount = document.getElementById('cantonSummaryCount');
    const cantonSummaryTotal = document.getElementById('cantonSummaryTotal');
    
    // 日料店控制元素
    const japaneseSubmitBtn = document.getElementById('japaneseSubmitOrderBtn');
    const japaneseSummaryCount = document.getElementById('japaneseSummaryCount');
    const japaneseSummaryTotal = document.getElementById('japaneseSummaryTotal');
    
    // 数量控制事件
    qtyControls.forEach(control => {
        const decrBtn = control.querySelector('[data-action="decr"]');
        const incrBtn = control.querySelector('[data-action="incr"]');
        const qtyInput = control.querySelector('.qty-input');
        
        decrBtn.addEventListener('click', () => {
            const currentValue = parseInt(qtyInput.value) || 0;
            if (currentValue > 0) {
                qtyInput.value = currentValue - 1;
                updateAllOrderSummaries();
            }
        });
        
        incrBtn.addEventListener('click', () => {
            const currentValue = parseInt(qtyInput.value) || 0;
            qtyInput.value = currentValue + 1;
            updateAllOrderSummaries();
        });
        
        qtyInput.addEventListener('input', updateAllOrderSummaries);
    });
    
    // 提交订单按钮事件
    if (sichuanSubmitBtn) {
        sichuanSubmitBtn.addEventListener('click', () => submitRestaurantOrder('川菜馆'));
    }
    if (cantonSubmitBtn) {
        cantonSubmitBtn.addEventListener('click', () => submitRestaurantOrder('粤菜馆'));
    }
    if (japaneseSubmitBtn) {
        japaneseSubmitBtn.addEventListener('click', () => submitRestaurantOrder('日料店'));
    }
    
    // 更新所有餐厅的订单摘要
    function updateAllOrderSummaries() {
        updateRestaurantSummary('川菜馆', sichuanSummaryCount, sichuanSummaryTotal, sichuanSubmitBtn);
        updateRestaurantSummary('粤菜馆', cantonSummaryCount, cantonSummaryTotal, cantonSubmitBtn);
        updateRestaurantSummary('日料店', japaneseSummaryCount, japaneseSummaryTotal, japaneseSubmitBtn);
    }
    
    // 更新单个餐厅的订单摘要
    function updateRestaurantSummary(restaurant, summaryCount, summaryTotal, submitBtn) {
        let totalCount = 0;
        let totalPrice = 0;
        
        // 获取该餐厅的所有菜品
        const restaurantCards = document.querySelectorAll(`[data-restaurant="${restaurant}"]`);
        restaurantCards.forEach(menuCard => {
            const qtyInput = menuCard.querySelector('.qty-input');
            const price = parseFloat(menuCard.dataset.price) || 0;
            const quantity = parseInt(qtyInput.value) || 0;
            
            totalCount += quantity;
            totalPrice += price * quantity;
        });
        
        if (summaryCount) summaryCount.textContent = totalCount;
        if (summaryTotal) summaryTotal.textContent = `¥${totalPrice.toFixed(2)}`;
        
        // 更新提交按钮状态
        if (submitBtn) {
            submitBtn.disabled = totalCount === 0;
            submitBtn.textContent = totalCount > 0 ? `提交${restaurant}订单 (¥${totalPrice.toFixed(2)})` : `提交${restaurant}订单`;
        }
    }
    
    // 提交单个餐厅的订单
    function submitRestaurantOrder(restaurant) {
        const orderItems = [];
        
        // 获取该餐厅的所有菜品
        const restaurantCards = document.querySelectorAll(`[data-restaurant="${restaurant}"]`);
        restaurantCards.forEach(menuCard => {
            const qtyInput = menuCard.querySelector('.qty-input');
            const quantity = parseInt(qtyInput.value) || 0;
            
            if (quantity > 0) {
                const menuName = menuCard.querySelector('.menu-name').textContent;
                const price = parseFloat(menuCard.dataset.price);
                
                orderItems.push({
                    name: menuName,
                    quantity: quantity,
                    price: price,
                    total: price * quantity,
                    restaurant: restaurant
                });
            }
        });
        
        if (orderItems.length === 0) {
            alert(`请选择至少一个${restaurant}商品`);
            return;
        }
        
        // 计算总金额
        const totalAmount = orderItems.reduce((sum, item) => sum + item.total, 0);
        
        // 构建订单数据
        const orderData = {
            items: orderItems,
            totalAmount: totalAmount,
            orderTime: new Date().toISOString(),
            customerName: getCurrentCustomerName() || '游客',
            status: 'pending',
            restaurant: restaurant
        };
        
        // 提交到后端
        submitOrderToBackend(orderData);
    }
    
    // 提交订单到后端
    function submitOrderToBackend(orderData) {
        // 显示加载状态
        const restaurant = orderData.restaurant;
        const submitBtn = document.getElementById(getRestaurantSubmitBtnId(restaurant));
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.textContent = '提交中...';
        
        apiService.submitOrder(orderData)
        .then(function(data) {
            console.log('订单提交成功:', data);
            
            // 显示成功消息
            alert(`订单提交成功！\n订单号：${data.orderNumber}\n总金额：¥${data.totalAmount.toFixed(2)}`);
            
            // 清空购物车
            clearRestaurantCart(restaurant);
            
            // 刷新订单列表
            loadRecentOrders();
        })
        .catch(function(error) {
            console.error('订单提交失败:', error);
            alert('订单提交失败，请重试：' + error.message);
        })
        .finally(function() {
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
        });
    }
    
    // 确定主要餐厅
    function determinePrimaryRestaurant(orderItems) {
        const restaurantCounts = {};
        
        // 统计每个餐厅的菜品数量
        orderItems.forEach(item => {
            const restaurant = item.restaurant || '川菜馆';
            restaurantCounts[restaurant] = (restaurantCounts[restaurant] || 0) + item.quantity;
        });
        
        // 找到菜品数量最多的餐厅
        let maxCount = 0;
        let primaryRestaurant = '川菜馆'; // 默认餐厅
        
        for (const restaurant in restaurantCounts) {
            if (restaurantCounts[restaurant] > maxCount) {
                maxCount = restaurantCounts[restaurant];
                primaryRestaurant = restaurant;
            }
        }
        
        return primaryRestaurant;
    }
    
    // 获取餐厅提交按钮ID
    function getRestaurantSubmitBtnId(restaurant) {
        switch (restaurant) {
            case '川菜馆': return 'sichuanSubmitOrderBtn';
            case '粤菜馆': return 'cantonSubmitOrderBtn';
            case '日料店': return 'japaneseSubmitOrderBtn';
            default: return 'submitOrderBtn';
        }
    }
    
    // 清空指定餐厅的购物车
    function clearRestaurantCart(restaurant) {
        const restaurantCards = document.querySelectorAll(`[data-restaurant="${restaurant}"]`);
        restaurantCards.forEach(menuCard => {
            const qtyInput = menuCard.querySelector('.qty-input');
            qtyInput.value = 0;
        });
        updateAllOrderSummaries();
    }
    
    // 获取当前客户名称
    function getCurrentCustomerName() {
        // 这里可以从用户登录信息或其他地方获取客户名称
        // 暂时返回默认值
        return '游客' + Math.floor(Math.random() * 1000);
    }
}

// 加载最近订单
function loadRecentOrders() {
    const ordersList = document.getElementById('ordersList');
    if (!ordersList) return;
    
    // 显示加载状态
    ordersList.innerHTML = `
        <div class="order-item" data-skeleton>
            <div class="order-info">
                <h5>加载中…</h5>
                <p>正在获取最近订单</p>
            </div>
            <span class="status-badge">···</span>
        </div>
    `;
    
    // 从后端接口获取订单历史
    apiService.getOrderHistory()
    .then(function(data) {
        console.log('订单历史数据:', data);
        updateRecentOrdersList(data.orders || []);
    })
    .catch(function(error) {
        console.error('获取订单历史失败:', error);
        showOrderHistoryError();
    });
}

// 更新最近订单列表
function updateRecentOrdersList(orders) {
    const ordersList = document.getElementById('ordersList');
    if (!ordersList) return;
    
    const recentOrders = orders.slice(0, 3); // 显示最近3个订单
    
    if (recentOrders.length === 0) {
        ordersList.innerHTML = `
            <div class="order-item">
                <div class="order-info">
                    <h5>暂无订单</h5>
                    <p>您还没有任何订单记录</p>
                </div>
                <span class="status-badge">-</span>
            </div>
        `;
        return;
    }
    
    ordersList.innerHTML = recentOrders.map(order => `
        <div class="order-item">
            <div class="order-info">
                <h5>订单 #${order.orderNumber}</h5>
                <p>${order.items.length}个商品 · ${formatOrderTime(order.orderTime)}</p>
            </div>
            <span class="status-badge ${order.status}">${getStatusText(order.status)}</span>
        </div>
    `).join('');
}

// 显示订单历史错误
function showOrderHistoryError() {
    const ordersList = document.getElementById('ordersList');
    if (!ordersList) return;
    
    ordersList.innerHTML = `
        <div class="order-item error">
            <div class="order-info">
                <h5>连接失败</h5>
                <p>无法获取订单数据</p>
            </div>
            <span class="status-badge error">错误</span>
        </div>
    `;
}

// 格式化订单时间
function formatOrderTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'pending': '待处理',
        'preparing': '制作中',
        'ready': '待取餐',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}
